﻿#include <QString>
#include <QApplication>
#include "JZTimerMessageBox.h"

JZTimerMessageBox::JZTimerMessageBox(const QString &text, 
                                   const QString &title,
                                   StandardButtons buttons,
                                   int timeoutMs,
                                   QWidget *parent)
    : QMessageBox(parent),
      m_remainingTime(timeoutMs / 1000),
      m_originalText(title)
{
    if (title.isEmpty())
    {
        m_originalText = qApp->applicationName();
    }

    setWindowTitle(m_originalText + QString(" (%1秒后关闭)").arg(m_remainingTime));
    setText(text);
    setStandardButtons(buttons);
    
    // 自动关闭定时器
    m_timer = new QTimer(this);
    m_timer->setSingleShot(true);
    m_timer->setInterval(timeoutMs);
    connect(m_timer, &QTimer::timeout, this, &JZTimerMessageBox::onTimeout);
    m_timer->start();
    
    // 倒计时更新定时器
    m_countdownTimer = new QTimer(this);
    m_countdownTimer->setInterval(1000); // 每秒更新一次
    connect(m_countdownTimer, &QTimer::timeout, this, &JZTimerMessageBox::updateCountdownText);
    m_countdownTimer->start();
}

void JZTimerMessageBox::information(QWidget *parent, 
                                   const QString &title, 
                                   const QString &text, 
                                   int timeoutMs)
{
    JZTimerMessageBox msgBox(text, title, QMessageBox::Ok, timeoutMs, parent);
    msgBox.setIcon(QMessageBox::Information);
    msgBox.exec();
}

void JZTimerMessageBox::warning(QWidget *parent, 
                              const QString &title, 
                              const QString &text, 
                              int timeoutMs)
{
    JZTimerMessageBox msgBox(text, title, QMessageBox::Ok, timeoutMs, parent);
    msgBox.setIcon(QMessageBox::Warning);
    msgBox.exec();
}

void JZTimerMessageBox::critical(QWidget *parent, 
                               const QString &title, 
                               const QString &text, 
                               int timeoutMs)
{
    JZTimerMessageBox msgBox(text, title, QMessageBox::Ok, timeoutMs, parent);
    msgBox.setIcon(QMessageBox::Critical);
    msgBox.exec();
}

void JZTimerMessageBox::onTimeout()
{
    // 自动关闭弹窗
    accept();
}

void JZTimerMessageBox::updateCountdownText()
{
    m_remainingTime--;
    if (m_remainingTime >= 0) {
        setWindowTitle(m_originalText + QString(" (%1秒后关闭)").arg(m_remainingTime));
    } else {
        m_countdownTimer->stop();
    }
}
